<template>
  <div class="support-page">
    <Container padding="0 3.125vw">
      <NavPanel
        :data="navPanelData"
        :activeId="navActiveId"
        @item-click="navPanelItemClick"
      />
      <!-- <Container class="support-container" padding-top="0"> -->
      <template v-if="tableShowIndex == 1">
        <TableTags :data="baseRepairData.tags" />
        <TableService
          @consult="consultService"
          :header="baseRepairData.header"
          :data="baseRepairData.data"
          type="基地维修"
        >
        </TableService>
      </template>
      <template v-if="tableShowIndex == 2">
        <TableTags :data="airLineData.tags" />
        <TableService2
          @consult="consultService"
          className="airline-table"
          :header="airLineData.header"
          :data="airLineData.data"
          type="航线服务"
        >
        </TableService2>
      </template>
      <template v-if="tableShowIndex == 3">
        <TableTags :data="componentModifyData.tags" />
        <TableService
          @consult="consultService"
          :header="componentModifyData.header"
          :data="componentModifyData.data"
          type="部件大修"
        >
        </TableService>
      </template>
      <template v-if="tableShowIndex == 4"> </template>
      <!-- </Container> -->
    </Container>
    <DialogService
      ref="dialogServiceRef"
      :supportData="dialogData"
    ></DialogService>
    <DialogMobileService
      ref="dialogMobileServiceRef"
      :supportData="dialogData"
    ></DialogMobileService>
  </div>
</template>

<script setup lang="ts">
import data from "./data.ts";
import { useCacheStore, useMemberStore } from "../../../store";
import { message } from "ant-design-vue";

const cacheStore = useCacheStore();
const memberStore = useMemberStore();

const tableShowIndex = ref();

// navpanel数据
const navActiveId = ref();
const navPanelData = ref<any[]>();
const navPanelItemClick = (item) => {
  navActiveId.value = item.value;
  resetShowTableData();
};

const resetShowTableData = () => {
  navPanelData.value!.forEach((item, index) => {
    if (item.value == navActiveId.value) {
      tableShowIndex.value = index + 1;
    }
  });
};

const dialogData = ref();
const dialogServiceRef = ref();
const dialogMobileServiceRef = ref();
const consultService = (data) => {
  if (!memberStore.profile) {
    message.warning($t("message.wait_login"));
    return;
  }
  dialogData.value = data;
  nextTick(() => {
    if (isMobile()) {
      dialogMobileServiceRef.value.show();
    } else {
      dialogServiceRef.value.show();
    }
  });
};
import { repaireHeaders, airLineHeaders } from "./data/header";
let { banner1Data, banner2Data, banner3Data } = data;
import {
  getCurrentInstance,
  nextTick,
  onMounted,
  provide,
  ref,
  toRaw,
  watch,
} from "vue";
import {
  postAirModel,
  postBaseRepairModel,
  postCompModifyModel,
  postAirLineServiceModel,
  postSupportCategoryList,
  postAirLineTableNew,
} from "../../../api/support";
import type { TableRowItem } from "../types/table";

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

// 获取部件大修数据
const postCompoModifyModelData = async () => {
  const res = await postCompModifyModel();
  if (res.code == 200) {
    let arr = res.data.map((item) => ({
      id: item.id,
      consult: $t("btnText.consult"),
      service: item.service_code,
      repair: item.repair_service_title,
      airport: item.list.map((item2) => {
        return item2.options;
      }),
    }));
    arr.sort((a, b) => {
      if (a.service.length < b.service.length) {
        return -1;
      }
      if (a.service.length > b.service.length && a.service > b.service) {
        return 1;
      }
      return 0;
    });
    componentModifyData.value.data = arr || [];
  } else {
    componentModifyData.value.data = [];
  }
  cacheStore.supportData.componentModify.table = componentModifyData.value;
};

const splitArrayData = (data?: any, _key?: any) => {
  return data.reduce((accumulator?: any, current?: any) => {
    const key = current[_key];
    if (!accumulator[key]) {
      accumulator[key] = [];
    }
    accumulator[key].push(current);
    return accumulator;
  }, {});
};

const resetTableData = () => {
  let data: any = [];
  airLineData.value.data.map((serviceItem) => {
    serviceItem.country?.map((countryItem, countryIndex) => {
      countryItem.airport.map((airportItem, airportItemIndex) => {
        let airportType: any[] = [];
        airportType.push(airportItem.airport_title);
        airportItem.airmodel.map((airmodelItem, airmodelIndex) => {
          let obj = Object.assign({}, airmodelItem);
          if (
            countryIndex == 0 &&
            airmodelIndex == 0 &&
            airportItemIndex == 0
          ) {
            obj.service_code = serviceItem.service_code;
            obj.service_code_count = serviceItem.service_code_count;
            obj.country_title = countryItem.country_title;
            obj.country_count = countryItem.country_count;
            obj.airport_count = airportItem.airport_count;
          }
          obj.service_code = serviceItem.service_code;
          obj.country_title = countryItem.country_title;
          obj.airport_title = airportItem.airport_title;
          // 响应式对象转普通对象
          Object.keys(obj).forEach((key) => (obj[key] = toRaw(obj[key])));
          data.push(obj);
        });
      });
    });
  });
  // 计算rowspan
  searchRowSpan(data);
  airLineData.value.data = data;
};

const searchRowSpan = (rawdata) => {
  let values = splitArrayData(rawdata, "service_code");
  // 服务代码
  (() => {
    let _key = "service_code";
    let row_index = 0;
    Object.keys(values).forEach((key, index) => {
      let blockArr = values[key];
      if (index == 0) {
        rawdata[index][_key + "_rowspan"] = blockArr.length;
      } else {
        rawdata[row_index][_key + "_rowspan"] = blockArr.length;
      }
      row_index += blockArr.length;
    });
  })();
  // 国家
  (() => {
    let row_index = 0;
    let _key = "country_title";
    Object.keys(values).forEach((key, index) => {
      let blockArr = values[key];
      let _values = splitArrayData(blockArr, _key);
      Object.keys(_values).forEach((key, index) => {
        let blockArr = _values[key];
        rawdata[row_index][_key + "_rowspan"] = blockArr.length;
        row_index += blockArr.length;
      });
    });
  })();
  // 机场
  (() => {
    let row_index = 0;
    let _key = "airport_title";
    Object.keys(values).forEach((key1, index) => {
      let blockArr = values[key1];
      let _values = splitArrayData(blockArr, "country_title");
      Object.keys(_values).forEach((key2, index) => {
        let blockArr = _values[key2];
        let __values = splitArrayData(blockArr, _key);
        Object.keys(__values).forEach((key3, index) => {
          let blockArr = __values[key3];
          rawdata[row_index][_key + "_rowspan"] = blockArr.length;
          row_index += blockArr.length;
        });
      });
    });
  })();
};

const getAirLineData = async () => {
  const res = await postAirLineTableNew();
  airLineData.value.data = res.data as never[];
  resetTableData();
};

const primaryKeys = [
  "service_code",
  "country_title",
  "airport_title",
  "airmodel_title",
  "engine_title",
];

// 重构航线服务数据结构
// 基地维修
const baseRepairData = ref({
  tags: [],
  data: [],
  title: "",
  header: repaireHeaders,
});
// 航线服务
const airLineData = ref({
  tags: [],
  data: [],
  title: "",
  header: airLineHeaders,
});
// 部件大修
const componentModifyData = ref({
  tags: [],
  data: [],
  title: "",
  header: repaireHeaders,
});

const fetching = ref(true);
provide("fetching", fetching);
const getNavPanelData = async () => {
  let res = await postSupportCategoryList();
  if (res.code === 200) {
    componentModifyData.value.title = res.data[0].title;
    airLineData.value.title = res.data[1].title;
    baseRepairData.value.title = res.data[2].title;
    navPanelData.value = [];
    navPanelData.value.push({
      value: res.data[0].id,
      label: res.data[0].title,
    });
    navPanelData.value.push({
      value: res.data[1].id,
      label: res.data[1].title,
    });
    navPanelData.value.push({
      value: res.data[2].id,
      label: res.data[2].title,
    });
    navActiveId.value = navPanelData.value[0].value;
    resetShowTableData();
    nextTick(() => {
      baseRepairData.value.tags = res.data[0].Article.map((item) => item.title);
      airLineData.value.tags = res.data[1].Article.map((item) => item.title);
      componentModifyData.value.tags = res.data[2].Article.map(
        (item) => item.title
      );
    });
  }
};

const getBaseRepairData = async () => {
  Promise.all([postAirModel(), postBaseRepairModel()]).then((res) => {
    let data1 = res[0].data.map((item) => {
      return item.title;
    });
    let data2 = res[1].data.map((item) => {
      let obj: TableRowItem = {
        id: item.id,
        consult: "咨询",
        service: item.service_code_title,
        repair: item.repair_service_title,
        airport: item.list.map((item2) => {
          return item2.options;
        }),
      };
      return obj;
    });
    baseRepairData.value.header[2].types = data1 || [];
    componentModifyData.value.header[2].types = data1 || [];
    baseRepairData.value.data = data2 || [];

    // 设置缓存
    cacheStore.supportData.baseRepair.types = data1;
    cacheStore.supportData.baseRepair.table = data2;

    cacheStore.supportData.componentModify.types = data1;
  });
};

const postData = async () => {
  fetching.value = true;
  await Promise.all([
    getBaseRepairData(),
    postCompoModifyModelData(),
    getAirLineData(),
    getNavPanelData(),
  ]);
  fetching.value = false;
};
postData()
</script>
<style scoped lang="less"></style>
